<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>学生成绩管理系统</title>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        body {
            background-image: url('/picture/info.jpg');
            background-size: cover;
            background-repeat: no-repeat;
            background-position: center;
            background-attachment: fixed;
            margin: 0;
            padding: 0;
        }
        .container {
            width: 800px;
            margin: 50px auto;
            padding: 20px;
            background-color: rgba(255, 255, 255, 0.9);
            border-radius: 5px;
        }
        .nav-tabs {
            display: flex;
            margin-bottom: 20px;
            border-bottom: 1px solid #ddd;
        }
        .nav-tab {
            padding: 10px 20px;
            cursor: pointer;
            border: 1px solid transparent;
            margin-bottom: -1px;
        }
        .nav-tab.active {
            border: 1px solid #ddd;
            border-bottom-color: white;
            background-color: white;
        }
        .tab-content {
            display: none;
        }
        .tab-content.active {
            display: block;
        }
        table {
            width: 100%;
            border-collapse: collapse;
        }
        th, td {
            padding: 8px;
            border: 1px solid #ddd;
            text-align: center;
        }
        th {
            background-color: #f5f5f5;
        }
        tr:hover {
            background-color: #f9f9f9;
        }
        .chart-container {
            margin-top: 20px;
            height: 400px;
        }
        .user-info {
            position: absolute;
            top: 20px;
            right: 20px;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <div class="user-info" onclick="showUserInfo()">
        👤 个人信息
    </div>
    <div class="container">
        <h1>学生成绩管理系统</h1>
        <div class="nav-tabs">
            <div class="nav-tab active" onclick="switchTab('scores')">查看成绩</div>
            <div class="nav-tab" onclick="switchTab('analysis')">成绩分析</div>
        </div>
        
        <div id="scores" class="tab-content active">
            <table>
                <thead>
                    <tr>
                        <th>考试日期</th>
                        <th>语文</th>
                        <th>数学</th>
                        <th>英语</th>
                        <th>总分</th>
                    </tr>
                </thead>
                <tbody id="scoreTable">
                </tbody>
            </table>
        </div>
        
        <div id="analysis" class="tab-content">
            <canvas id="scoreChart"></canvas>
        </div>
    </div>

    <script>
        let studentId = null;
        let scoreData = [];
        let chart = null;

        // 页面加载时获取用户信息和成绩数据
        window.onload = function() {
            console.log('Checking user session...');
            studentId = sessionStorage.getItem('userId');
            console.log('Stored userId:', studentId);
            
            if (!studentId) {
                console.log('No user session found - redirecting to login');
                alert('请先登录！');
                window.location.replace('login.html');
                return;
            }
            
            console.log('User session found - loading student page');
            loadScores();
        };

        // 加载成绩数据
        function loadScores() {
            fetch(`/api/scores/${studentId}`)
                .then(response => response.json())
                .then(data => {
                    scoreData = data;
                    updateScoreTable();
                    updateScoreChart();
                })
                .catch(error => {
                    console.error('获取成绩失败：', error);
                    alert('获取成绩数据失败');
                });
        }

        // 更新成绩表格
        function updateScoreTable() {
            const tbody = document.getElementById('scoreTable');
            tbody.innerHTML = '';
            
            scoreData.forEach(score => {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>${score.examDate}</td>
                    <td>${score.chineseScore}</td>
                    <td>${score.mathScore}</td>
                    <td>${score.englishScore}</td>
                    <td>${score.totalScore}</td>
                `;
                tbody.appendChild(row);
            });
        }

        // 更新成绩图表
        function updateScoreChart() {
            const ctx = document.getElementById('scoreChart').getContext('2d');
            
            if (chart) {
                chart.destroy();
            }
            
            const labels = scoreData.map(score => score.examDate);
            const datasets = [
                {
                    label: '语文',
                    data: scoreData.map(score => score.chineseScore),
                    borderColor: 'rgb(255, 99, 132)',
                    tension: 0.1
                },
                {
                    label: '数学',
                    data: scoreData.map(score => score.mathScore),
                    borderColor: 'rgb(54, 162, 235)',
                    tension: 0.1
                },
                {
                    label: '英语',
                    data: scoreData.map(score => score.englishScore),
                    borderColor: 'rgb(75, 192, 192)',
                    tension: 0.1
                },
                {
                    label: '总分',
                    data: scoreData.map(score => score.totalScore),
                    borderColor: 'rgb(153, 102, 255)',
                    tension: 0.1
                }
            ];

            chart = new Chart(ctx, {
                type: 'line',
                data: {
                    labels: labels,
                    datasets: datasets
                },
                options: {
                    responsive: true,
                    scales: {
                        y: {
                            beginAtZero: true
                        }
                    }
                }
            });
        }

        // 切换标签页
        function switchTab(tabId) {
            document.querySelectorAll('.nav-tab').forEach(tab => {
                tab.classList.remove('active');
            });
            document.querySelectorAll('.tab-content').forEach(content => {
                content.classList.remove('active');
            });
            
            document.querySelector(`.nav-tab[onclick="switchTab('${tabId}')"]`).classList.add('active');
            document.getElementById(tabId).classList.add('active');
            
            if (tabId === 'analysis' && scoreData.length > 0) {
                updateScoreChart();
            }
        }

        // 显示用户信息
        function showUserInfo() {
            const userId = sessionStorage.getItem('userId');
            const username = sessionStorage.getItem('username');
            const major = sessionStorage.getItem('major');
            const className = sessionStorage.getItem('className');
            const isAdmin = parseInt(sessionStorage.getItem('isAdmin')) === 1;
            
            const info = `
                ID: ${userId || '未知'}
                用户名: ${username || '未知'}
                专业: ${major || '未知'}
                班级: ${className || '未知'}
                身份: ${isAdmin ? '管理员' : '学生'}
            `;
            
            const applyAdmin = confirm(info + '\n\n是否申请成为管理员？');
            if (applyAdmin) {
                const secretKey = prompt('请输入管理员秘钥：');
                if (secretKey === 'huang') {
                    applyForAdmin(userId);
                } else {
                    alert('秘钥错误！');
                }
            }
        }

        function applyForAdmin(userId) {
            fetch(`/api/auth/apply-admin/${userId}`, {
                method: 'POST'
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('申请成功！请重新登录。');
                    window.location.href = '/login.html';
                } else {
                    alert('申请失败：' + data.message);
                }
            })
            .catch(error => {
                alert('申请失败：' + error.message);
            });
        }
    </script>
</body>
</html> 